package org.jeecg.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.minio.errors.*;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.jeecg.domain.InstitutionStaff;
import org.jeecg.domain.vo.UserInfoVo;
import org.jeecg.file.service.FileStorageService;
import org.jeecg.service.InstitutionStaffService;
import org.jeecg.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

@RestController
@RequestMapping("certificate")
public class CertificateController {

    @Autowired
    private XszOcrUtils xszOcrUtils;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private InstitutionStaffService institutionStaffService;

    private  String realName;
    private  String idCard;
    private  String isoks;
    private String image;

    @PostMapping("discern")
    public String discern(MultipartFile file) throws Exception {
        UserInfoVo userInfoVo = new UserInfoVo();
        Result result = xszOcrUtils.checkFile(file);
        Object data = result.get("data");
        // 解析JSON字符串
        JSONObject jsonObject = JSON.parseObject(String.valueOf(data));
        String s = fileStorageService.uploadImageFile(file.getOriginalFilename(), file.getInputStream());
        image= s;
        // 读取姓名
        String name = jsonObject.getJSONObject("words_result").getJSONObject("姓名").getString("words");
        realName= name;
        userInfoVo.setRealName(name);
        // 读取公民身份号码
        String idCardNumber = jsonObject.getJSONObject("words_result").getJSONObject("公民身份号码").getString("words");
        idCard= idCardNumber;
        userInfoVo.setCardNo(idCardNumber);
        Result activeUser = AuthenticationUtils.getActiveUser(userInfoVo);
        Object data1 = activeUser.get("data");
        JSONObject jsonObject1 = JSON.parseObject(String.valueOf(data1));
        String isok = jsonObject1.getJSONObject("result").getString("isok");
        if (isok.equals("true")){
            isoks= isok;
            return s;
        }else {
            return "认证失败";
        }
    }

    @PostMapping("checkIdcard/{id}")
    public Result checkIdcard(@PathVariable Long id) {
        if (isoks.equals("true")){
            InstitutionStaff institutionStaff = new InstitutionStaff();
            institutionStaff.setId(String.valueOf(id));
            institutionStaff.setIdCardNo(idCard);
            institutionStaff.setRealname(realName);
            institutionStaff.setStatusId(1);
            institutionStaff.setImage(image);
            institutionStaffService.updateById(institutionStaff);
            return Result.success("认证成功");
        }else {
            return Result.error("认证失败");
        }
    }


    @PostMapping("aaa")
    public Result ocrIdCard(@RequestParam("file") MultipartFile file) throws IOException, ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        String image=fileStorageService.uploadImageFile(file.getOriginalFilename(), file.getInputStream());
        JSONObject result = new JSONObject();

        if (file.isEmpty()) {
            result.put("error", "请选择上传的文件");
            return Result.success(result);
        }

        String imgBase64 = AliIDConfig.imgBase64(file);

        // configure配置
        JSONObject configObj = new JSONObject();
        configObj.put("side", "face");

        // 创建请求对象
        JSONObject requestObj = new JSONObject();
        requestObj.put("image", imgBase64);
        if (configObj.size() > 0) {
            requestObj.put("configure", configObj);
        }

        try {
            HttpResponse response =  HttpUtils.doPost(
                    AliIDConfig.ALI_API_HOST,
                    AliIDConfig.ALI_API_PATH,
                    "POST",
                    AliIDConfig.buildHeaders(),
                    new HashMap<>(),
                    requestObj.toJSONString() // 使用toJSONString()将JSONObject转换为字符串
            );

            int stat = response.getStatusLine().getStatusCode();
            if (stat != 200) {
                result.put("error", "Http code: " + stat);
                result.put("message", EntityUtils.toString(response.getEntity()));
            } else {
                String res = EntityUtils.toString(response.getEntity());
                result = JSON.parseObject(res);
            }
        } catch (Exception e) {
            result.put("error", "OCR API调用失败");
            result.put("message", e.getMessage());
            // 记录错误而不仅仅打印堆栈跟踪
            e.printStackTrace();
        }

        System.out.println("aaa"+ result);
//        return checkIdcard(result.get("num"), result.get("name"));
        return Result.success(result.get("num"));
    }


}
